<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
date_default_timezone_set("Asia/Shanghai");
require __DIR__ . "/../lib/user.php";
require __DIR__ . "/../lib/arcitle.php";
$pdo = require __DIR__ . "/../lib/db.php";

/**
 *
 */
class Restful
{
    private $_user;
    private $_arcitle;
    /**
     * 请求方法
     * @var string
     */
    private $_requestMethod;
    private $_resourceName;
    private $_id;
    /**
     * 允许请求资源列表
     * @var array
     */
    private $_allowResources = ['users', 'arcitles'];
    /**
     * 允许请求方法
     * @var array
     */
    private $_allowRequestMethods = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'];
    private $_statusCode = [
        200 => "ok",
        204 => "No Content",
        400 => "Bad Request",
        401 => "Unauthorized",
        403 => "Forbidden",
        404 => "Not Found",
        405 => "Method not Allowed",
        500 => "Server Interval Error"
    ];

    /**
     * Restful constructor.
     * @param $_user
     * @param $_arcitle
     */
    public function __construct($_user, $_arcitle)
    {
        $this->_user = $_user;
        $this->_arcitle = $_arcitle;
    }

    public function run()
    {
        try {
            $this->_setupRequestMethod();
            $this->_setupResource();
            if($this->_resourceName == "users"){
               return $this->_json($this->_handleUser());     
            }else{
              return $this->_json($this->_handleArtcle()) ;
            }
        } catch (Exception $e) {
            $this->_json(['error' => $e->getMessage()], $e->getCode());
        }
    }
    
    private function _handleUser(){
        if($this->_requestMethod != 'POST'){
            throw new Exception("請求方法不被允許", 405);
        }   
        $body = $this->_getBodyParams(); 
        if(empty($body['username'])){
            throw new Exception("用戶名不能爲空", 400);
        }
        if(empty($body['password'])){
            throw new Exception("密碼不能爲空", 400);
        }
        return $this->_user->register($body['username'],$body['password']);
    }

    private function _handleArtcle(){
        switch ($this->_requestMethod) {
            case 'POST':
                return $this->_handleArticleCreate();
                break;
            case 'GET' :
                if(empty($this->_id)){
                   return $this->_handleArticleList();
                }else{
                    return $this->_handleArticleView();
                }
                break ;
            case 'PUT' :
                return $this->_handleArticleEdit();
                break ;
            case 'DELETE' :
                return $this->_handleArticleDelete();
                break ;    
            default:
                # code...
                break;
        }
    }
    private function _handleArticleCreate(){

    }
    private function _handleArticleList(){
        
    }
    private function _handleArticleView(){
        
    }
    private function _handleArticleEdit(){
        
    }
    private function _handleArticleDelete(){
        
    }


    private function _getBodyParams(){
        $raw = file_get_contents("php://input");
        if(empty($raw)){
            throw new Exception("請求參數輸錯", 400);
        }
        return json_decode($raw,true);
    }

    private function _setupRequestMethod()
    {
        $this->_requestMethod = $_SERVER['REQUEST_METHOD'];
        if (!in_array($this->_requestMethod, $this->_allowRequestMethods)) {
            throw  new Exception("方法不被允许", 405);
        }
    }

    private function _setupResource()
    {
        $path = $_SERVER['PATH_INFO'];
        $params = explode("/", $path);
        $this->_resourceName = $params[1];
        if(!in_array($this->_resourceName,$this->_allowResources)){
            throw new Exception("請求資源不被允許", 400);
        }
        if (!empty($params[2])) {
            $this->_id = $params[2];
        }
    }

    private function _json($array, $code = 0)
    {
        if ($code > 0 && $code !== 200 && $code !== 204) {
            header("HTTP/1.1 " . $code . " " . $this->_statusCode[$code]);
        } else {
            header("Content-type:application/json;charset=utf-8");
            echo json_encode($array, JSON_UNESCAPED_UNICODE);
            exit();
        }
    }
}

$User = new User($pdo);
$Arcitle = new Arcitle($pdo);

$result = new Restful($User, $Arcitle);
$result->run();

